package cn.yr.system.controller;

import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.domain.entity.SysUser;
import cn.yr.common.core.manager.AuthCacheManager;
import cn.yr.common.core.utils.jwt.JwtUtil;
import cn.yr.oauth.manager.OAuthManager;
import cn.yr.system.service.ISysUserService;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author Lang 1102076808@qq.com
 * @description web用户
 * @date 2020-07-19 20:19
 */
@Controller
@RequestMapping("/oauth2")
public class LoginOAuth2Controller{

	@Resource
	private OAuthManager authManager;
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private AuthCacheManager authCacheManager;

	@Value("${oauth.waitUrl}")
	private String waitUrl;
	/**
	 * 获取授权链接并跳转到第三方授权页面
	 */
	@RequestMapping("/renderAuth/{oauthType}")
	public String renderAuth(@PathVariable String oauthType) {
		return "redirect:"+getAuthorizeUrl(oauthType);
	}

	@RequestMapping("/getAuthorizeUrl/{oauthType}")
	@ResponseBody
	public String getAuthorizeUrl(@PathVariable String oauthType){
		AuthRequest authRequest = authManager.getAuthRequest(oauthType);
		return authRequest.authorize(AuthStateUtils.createState());
	}

	/**
	 * 用户在确认第三方平台授权（登录）后， 第三方平台会重定向到该地址，并携带code、state等参数
	 * @param callback 第三方回调时的入参
	 * @return 第三方平台的用户信息
	 */
	@RequestMapping("/callback/{oauthType}")
	public String callback(@PathVariable String oauthType, AuthCallback callback) {
		AuthRequest authRequest =  authManager.getAuthRequest(oauthType);
		AuthResponse authResponse = authRequest.login(callback);
		AuthUser authUser = (AuthUser)authResponse.getData();
		SysUserDto sysUserDto = sysUserService.coverSysUser(authUser);
		SysUser user = sysUserDto.getSysUser();
		authCacheManager.putUser(user.getUserId().toString(),sysUserDto);
		/** 返回token*/
		String token = JwtUtil.generateToken(user.getUserId().toString());
		return "redirect:" + waitUrl+token;
	}

}
